<?php

namespace backend\modules\rbac\controllers;

use backend\models\Admin;
use backend\modules\base\controllers\BaseController;
use backend\modules\rbac\models\AuthAssignment;
use backend\modules\rbac\models\AuthItem;
use backend\modules\rbac\models\AuthItemChild;
use backend\modules\rbac\models\Menu;
use backend\modules\rbac\models\MenuPerm;
use Yii;
use yii\base\Exception;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;

/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['index','create','view','update','addUser','move','getmenuperm','roles','setrole'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        $adminARR = Admin::find()->all();
        return $this->render('index',['adminARR'=>$adminARR]);
    }

    /**
     * 创建后台用户
     *
     * Lists all User models.
     * @return mixed
     */
    public function actionCreate()
    {
        $post = Yii::$app->request->post();
        $postData = isset($post['data'])?$post['data']:'';
        if($postData) {
            $admin = new Admin();
            try{
                $admin->signup($postData);
                return $this->redirect(['index']);
            }catch (Exception $e){
                return json_encode(['code'=>500,'message'=>$e->getMessage()]);
            }
        }
    }

    /**
     * 获取用户角色列表
     *
     * @return string
     */
    public function actionRoles()
    {
        $post = Yii::$app->request->post();
        $postData = isset($post['data'])?$post['data']:'';
        if($postData){
            $roles = AuthItem::find()->where(['type'=>1])->asArray()->all();
            $userRoles = AuthAssignment::find()
                ->select('ai.name,ai.type,ai.description,ai.rule_name,ai.data,ai.created_at,ai.updated_at')
                ->from('auth_assignment as aa')
                ->leftJoin('auth_item as ai','ai.name=aa.item_name')
                ->where(['user_id'=>$postData['userid']])->asArray()->all();
            foreach($roles as $k=>$v) {
                if(in_array($v,$userRoles)){
                    $v['checked'] = true;
                } else {
                    $v['checked'] = false;
                }
                $roles[$k] = $v;
            }

            return json_encode(['code'=>200,'roles'=>$roles]);
        }
        return json_encode(['code'=>500]);
    }

    /**
     * 设置用户角色
     *
     * @return string
     * @throws \Exception
     * @throws \Throwable
     * @throws \yii\db\Exception
     */
    public  function  actionSetrole()
    {
        $post = Yii::$app->request->post();
        $userid = isset($post['userid'])?$post['userid']:'';
        if($userid){
            $newitemARR = array();
            $itemARR = AuthAssignment::find()->select(['item_name'])->where(['user_id'=>$userid])->asArray()->all();
            foreach($itemARR as $k=>$v) {
                $newitemARR[] = $v['item_name'];
            }
            $delRole = array_diff($newitemARR,$post['roleARR']);
            $addRole = array_diff($post['roleARR'],$newitemARR);
            $beginTransaction = Yii::$app->db->beginTransaction();
            try{
                foreach($delRole as $k=>$v) {
                    if(!AuthAssignment::findOne(['item_name'=>$v,'user_id'=>$userid])->delete()){
                        throw new Exception("删除失败");
                    }
                }
                foreach($addRole as $k=>$v) {
                    $newAssignmentModel = new AuthAssignment();
                    $newAssignmentModel->item_name = $v;
                    $newAssignmentModel->user_id = $userid;
                    if(!$newAssignmentModel->save())
                    {
                        throw new Exception(json_encode($newAssignmentModel->errors));
                    }
                }
                $beginTransaction->commit();
            }catch (Exception $e){
                $beginTransaction->rollBack();
                return json_encode(['code'=>500,'message'=>$e->getMessage()]);
            }

        }
        return json_encode(['code'=>200,'message'=>'ok']);
    }
}
